package leetcodeauto.common;


/**
 * LeetCode 专用 节点
 */
public class ListNode {
    public int val;
    public ListNode next;

    public ListNode() {
    }

    public ListNode(int val) {
        this.val = val;
    }

    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }

    public String toString() {
        return String.valueOf(val);
    }

    public String prettyString() {
        StringBuilder sb = new StringBuilder();
        String sep = "->";
        int count = 0;
        ListNode curr = this;
        while (curr != null && count < Integer.MAX_VALUE) { // 防止环
            sb.append(curr.val).append(sep);
            curr = curr.next;
            count++;
        }
        sb.delete(Math.max(0, sb.length() - sep.length()), sb.length());
        // 10, 1->2->3
        return count + ", " + sb;
    }

    public static ListNode from(int[] vals) {
        if (vals == null || vals.length == 0) {
            return null;
        }
        ListNode d, tail;
        d = tail = new ListNode();
        for (int i = 0; i < vals.length; i++) {
            tail = tail.next = new ListNode(vals[i]);
        }
        return d.next;
    }

}
